package com.fnzx.util.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * @author Wang Zhifu
 * @create 2021/10/26 14:01
 * @Description
 */
public class JwtUtil {
    /**
     * token签名密钥，随意设置仅自己知道就好
     */
    private static final String SIGNATURE ="I'M_ADMINISTRATOR12138";
    /**
     * token过期时间，2小时
     */
    private static final int EXPIRE_TIME = 60 * 60 * 24;

    /**
     * 根据用户信息创建token
     * @param payload 负载---> #用户信息
     * @return token
     */
    public static String createToken(HashMap<String,String> payload){
        //设置有效时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,EXPIRE_TIME);
        Date expireTime = instance.getTime();

        //设置加密算法
        Algorithm algorithm = Algorithm.HMAC256(SIGNATURE);

        JWTCreator.Builder builder= JWT.create();
        payload.forEach(builder::withClaim);
        String token = builder.withExpiresAt(expireTime).sign(algorithm);
        System.out.println(token);
        return token;
    }

    /**
     * 获取token的信息根据某个键
     * @param token token
     * @param key key
     * @return key--->value
     */
    public static String getPayloadInfo(String token,String key){
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim(key).asString();
    }

    /**
     * 验证token是否正确
     * @param token
     * @return
     */
    public static boolean verityToken(String token){
        System.out.println(token);
        Algorithm algorithm=Algorithm.HMAC256(SIGNATURE);
        try {
            JWTVerifier verify = JWT.require(algorithm).build();
            DecodedJWT decodedJwt = verify.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }
    }
}
